import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {ActionSheetController, LoadingController} from "ionic-angular";
import {ImagePicker, ImagePickerOptions} from "@ionic-native/image-picker";
import {FileTransferObject, FileTransfer} from "@ionic-native/file-transfer";
import {Camera, CameraOptions} from '@ionic-native/camera';
import {ApiProvider} from "../api/api";
import {Base64} from '@ionic-native/base64';
import { File,FileEntry } from '@ionic-native/file';
import {Observable} from "rxjs/Observable";

/*
  Generated class for the ImgUploadProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class ImgUploadProvider {
  avatar;

  public user_id;
  public oldUserImage;
  uploadImgStr;
  public Type;
  public maxUploadCount=1;

  // 调用相机时传入的参数
  private cameraOpt: CameraOptions = {
    quality: 100,
    allowEdit: true,
    targetWidth: 1200,
    targetHeight: 1200,
    saveToPhotoAlbum: true,
    sourceType:1,
    destinationType:this.camera.DestinationType.DATA_URL
  };

// 调用相册时传入的参数
/*  private imagePickerOpt = {
    maximumImagesCount: this.maxUploadCount,//选择一张图片
    width: 800,
    height: 800,
    quality: 80,
    outputType:1
  };*/

// 图片上传的的api
  public uploadApi:string;

  loading;

 public upload: any= {
    success: (data)=> { },//图片上传成功后的回调
    error: (err)=> { },//图片上传失败后的回调
    listen: ()=> { }//监听上传过程
  };

  constructor(public http: HttpClient,
              private actionSheetCtrl:ActionSheetController,
              private camera:Camera,
              private imagePicker:ImagePicker,
              private transfer:FileTransfer,
              private fileTransfer:FileTransferObject,
              private api:ApiProvider,
              private base64:Base64,
              private file:File,
              private loadingCtrl:LoadingController)
  {
    this.fileTransfer= this.transfer.create();
  }

  /**
   * 弹出页面筛选
   */
  showPicActionSheet() {
    this.useASComponent();
  }

  /**
   * 构造ActionSheet组件
   */
  private useASComponent() {
    let actionSheet=
      this.actionSheetCtrl.create({
        title: '请选择',
        buttons: [
          {
            text: '拍照',
            handler: ()=> {
              this.cameraOpt.sourceType=1;
              this.startCamera();
            }
          },
          {
            text: '从相册中选择',
            handler: ()=> {
              //this.cameraOpt.sourceType=0;
              //this.startCamera();
              this.openImgPicker();
            }
          },
          {
            text: '取消',
            role: 'cancel',
            handler: ()=> {
            }
          }
        ]
      });

    actionSheet.present();
  }

  /**
   * 启动拍照功能
   */
  private startCamera() {
    this.camera.getPicture(this.cameraOpt).then((imageData)=>
    {
      this.uploadImg(imageData);
    }, (err)=>{
      if(err=="No Image Selected")
      {
        return;
      }
      else
      {
        this.api.showToast('ERROR:'+ err,'bottom');//错误：无法使用拍照功能！
      }
    });
  }

  /**
   * 打开手机相册
   */
  private openImgPicker() {
  let imagePickerOpt = {
      maximumImagesCount: this.maxUploadCount,//选择一张图片
      width: 800,
      height: 800,
      quality: 80,
      outputType:1
    };

    this.imagePicker.getPictures(imagePickerOpt).then(images => {
      for(let i=0;i<images.length;i++)
      {
        this.uploadImgPicker(images[i]);
/*        this.avatar = images[i].slice(7);
        let filePath: string = this.avatar

        this.base64.encodeFile(filePath).then((base64File: string) => {
          this.uploadImg(base64File.substring(base64File.indexOf("base64")+7));
        }, (err) => {
          console.log(err);
        });*/
      }
    }).catch(err => {
      //observer.error(false);
    });
  }

  // 上传图片
  private uploadImgPicker(path: string) {
    if(!path) {
      return;
    }

    let fileTransfer = new FileTransfer();

    let options: any;
    options = {
      fileKey: 'file',
      headers: {},
      params: {type:this.Type}
    };
    this.fileTransfer.upload(path, this.api.url+'/userstu/uploadFile.do', options)
      .then((data) => {
        this.upload.success(JSON.parse(data.response));
/*        if(this.upload.success) {
          this.upload.success(JSON.parse(data.response));
        }*/
      }, (err) => {
        if(this.upload.error)
        {
          this.upload.error(err);
        }
        else
        {
          this.api.showToast("上传失败！","bottom")
        }
      });
  }

  /**
   * 上传图片
   * @param {string} path
   */
  private uploadImg(path:string) {
    // this.loading = this.loadingCtrl.create({
    //   content: '上传中...'
    // });

    //this.loading.present();

    if (!path) {
      return;
    }
    this.uploadImgStr=path;

    this.api.post(this.uploadApi,{img:this.uploadImgStr,imgpath:this.oldUserImage,userId:this.user_id,Type:this.Type}).subscribe(item=>{
      this.upload.success(item);
    },error => {
      this.upload.error(error);
    })
  }
}
